<?php
require __DIR__ . '/init.php';
session_start();

if (!isset($_SESSION['username'])) {
    header('Location: welcome.php');
    exit();
}

// 更新当前用户的在线状态（确保访问此页面也被记录为在线）
function updateUserOnlineStatus($username) {
    $onlineFile = 'online_users.dat';
    $user_ip = $_SERVER['REMOTE_ADDR'];
    $current_time = time();

    // 读取在线用户数据
    $online_users = [];
    if (file_exists($onlineFile)) {
        $online_users = unserialize(file_get_contents($onlineFile));
        if (!is_array($online_users)) {
            $online_users = [];
        }
    }

    // 更新当前用户状态
    $online_users[$username] = [
        'ip' => $user_ip,
        'last_active' => $current_time,
        'user_agent' => $_SERVER['HTTP_USER_AGENT']
    ];

    // 清理超时用户
    foreach ($online_users as $key => $user) {
        if ($current_time - $user['last_active'] > 300) { // 5分钟超时
            unset($online_users[$key]);
        }
    }

    // 保存数据
    file_put_contents($onlineFile, serialize($online_users));
}

// 更新当前用户的在线状态
updateUserOnlineStatus($_SESSION['username']);

// 获取所有注册用户
function getAllUsers() {
    $users = [];
    $userDir = __DIR__ . '/user';
    
    if (is_dir($userDir)) {
        $userFolders = scandir($userDir);
        foreach ($userFolders as $folder) {
            if ($folder !== '.' && $folder !== '..' && is_dir("$userDir/$folder")) {
                $users[] = $folder;
            }
        }
    }
    
    return $users;
}

// 获取在线用户数据
function getOnlineUsers() {
    $onlineFile = 'online_users.dat';
    $users = [];
    
    if (file_exists($onlineFile)) {
        $online_users = unserialize(file_get_contents($onlineFile));
        if (is_array($online_users)) {
            $users = $online_users;
        }
    }
    
    return $users;
}

// 获取用户注册时间
function getUserRegistrationTime($username) {
    $userInfoFile = __DIR__ . "/user/$username/info.json";
    if (file_exists($userInfoFile)) {
        $userInfo = json_decode(file_get_contents($userInfoFile), true);
        return $userInfo['created_at'] ?? time();
    }
    return time();
}

// 检查用户是否在线
function isUserOnline($username, $onlineUsers) {
    if (!isset($onlineUsers[$username])) return false;
    
    $lastActive = $onlineUsers[$username]['last_active'] ?? 0;
    $timeout = 300; // 5分钟超时
    
    return (time() - $lastActive) < $timeout;
}

// 获取用户头像路径或生成动态头像
function getUserAvatar($username) {
    $userDir = __DIR__ . "/user/$username";
    
    // 支持的图片扩展名
    $imageExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'];
    
    // 扫描用户目录查找图片文件
    if (is_dir($userDir)) {
        $files = scandir($userDir);
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            
            $filePath = "$userDir/$file";
            $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            
            if (in_array($ext, $imageExtensions)) {
                return "/user/$username/$file";
            }
        }
    }
    
    // 找不到头像时生成动态头像
    return "data:image/svg+xml;charset=UTF-8,".rawurlencode('
        <svg xmlns="http://www.w3.org/2000/svg" width="120" height="120" viewBox="0 0 120 120">
            <defs>
                <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
                    <stop offset="0%" stop-color="#'.substr(md5($username), 0, 6).'" />
                    <stop offset="100%" stop-color="#'.substr(md5($username), 10, 6).'" />
                </linearGradient>
            </defs>
            <circle cx="60" cy="60" r="55" fill="url(#grad)" />
            <text x="50%" y="60%" text-anchor="middle" font-family="Arial, sans-serif" 
                  font-size="48" fill="white" dominant-baseline="middle">
                '.mb_strtoupper(mb_substr($username, 0, 1)).'
            </text>
        </svg>
    ');
}

$allUsers = getAllUsers();
$onlineUsers = getOnlineUsers();

// 分离在线和离线用户
$onlineUserList = [];
$offlineUserList = [];

foreach ($allUsers as $username) {
    if (isUserOnline($username, $onlineUsers)) {
        $onlineUserList[] = $username;
    } else {
        $offlineUserList[] = $username;
    }
}

// 合并用户列表（在线用户在前）
$sortedUsers = array_merge($onlineUserList, $offlineUserList);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线用户 - JIILCHAT</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            background: linear-gradient(135deg, #141e30, #243b55);
            color: #f0f0f0;
            margin: 0;
            padding: 0;
            min-height: 100vh;
            overflow-x: hidden;
        }
        
        /* 顶栏样式 */
        .chat-app-header {
            background: linear-gradient(90deg, #1a2a6c, #2a5298);
            color: white;
            padding: 12px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 100;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            height: 70px;
        }
        
        .header-left {
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        
        .chat-app-header h1 {
            margin: 0;
            font-size: 18px;
            font-weight: 700;
            letter-spacing: 0.5px;
        }
        
        .chat-app-header h2 {
            margin: 2px 0 0;
            font-size: 13px;
            font-weight: 400;
            color: #a0c6ff;
            opacity: 0.9;
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.15);
            border: none;
            color: white;
            padding: 8px 16px;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .back-btn i {
            font-size: 16px;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-2px);
        }
        
        /* 顶部提示信息 */
        .info-banner {
            background: rgba(231, 76, 60, 0.15);
            border: 1px solid rgba(231, 76, 60, 0.3);
            border-radius: 8px;
            padding: 12px 15px;
            margin: 75px 15px 10px;
            text-align: center;
            font-size: 14px;
            color: #ffcccb;
            backdrop-filter: blur(5px);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .info-banner i {
            font-size: 18px;
            flex-shrink: 0;
        }
        
        .info-banner-content {
            max-width: 600px;
        }
        
        /* 用户列表样式 */
        .user-list {
            padding: 15px 10px 80px;
        }
        
        .user-card {
            display: flex;
            align-items: center;
            padding: 18px 15px;
            background: rgba(255, 255, 255, 0.08);
            border-radius: 15px;
            margin-bottom: 12px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.05);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        /* 在线用户高亮样式 */
        .user-card.online {
            background: rgba(46, 204, 113, 0.15);
            border: 1px solid rgba(46, 204, 113, 0.3);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
        }
        
        .user-card:hover {
            background: rgba(255, 255, 255, 0.12);
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }
        
        .user-card:active {
            transform: translateY(0);
        }
        
        .user-avatar {
            width: 55px;
            height: 55px;
            margin-right: 15px;
            border-radius: 50%;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
            background: linear-gradient(135deg, #3498db, #2c3e50);
            flex-shrink: 0;
            position: relative;
            border: 2px solid rgba(255, 255, 255, 0.1);
        }
        
        .user-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            background-color: #f0f0f0;
        }
        
        .user-info {
            flex-grow: 1;
            min-width: 0;
        }
        
        .user-card h3 {
            margin: 0;
            font-size: 17px;
            font-weight: 600;
            color: white;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        /* 在线状态指示器 */
        .online-indicator {
            display: flex;
            align-items: center;
            font-size: 13px;
            margin-top: 5px;
            color: #a0c6ff;
        }
        
        .online-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 6px;
            display: inline-block;
        }
        
        .online {
            background-color: #2ecc71;
            box-shadow: 0 0 6px #2ecc71;
        }
        
        .offline {
            background-color: #95a5a6;
        }
        
        /* 用户详情 */
        .user-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-top: 10px;
        }
        
        .detail-item {
            background: rgba(41, 128, 185, 0.2);
            border-radius: 8px;
            padding: 10px;
        }
        
        .detail-label {
            font-size: 12px;
            color: #a0c6ff;
            margin-bottom: 5px;
        }
        
        .detail-value {
            font-size: 14px;
            color: white;
        }
        
        .time-value {
            font-size: 13px;
        }
        
        /* 底部导航栏 */
        footer {
            position: fixed;
            bottom: 0;
            width: 100%;
            display: flex;
            justify-content: space-around;
            padding: 10px 0;
            background: rgba(10, 25, 47, 0.95);
            backdrop-filter: blur(10px);
            border-top: 1px solid rgba(255, 255, 255, 0.08);
            z-index: 100;
            box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .nav-btn {
            background: none;
            border: none;
            color: #a0c6ff;
            font-size: 14px;
            cursor: pointer;
            padding: 12px 20px;
            border-radius: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
            transition: all 0.3s ease;
            opacity: 0.7;
        }
        
        .nav-btn.active {
            color: #3498db;
            opacity: 1;
            transform: translateY(-5px);
        }
        
        .nav-btn i {
            font-size: 22px;
            transition: all 0.3s ease;
        }
        
        .nav-btn.active i {
            color: #3498db;
            text-shadow: 0 0 8px rgba(52, 152, 219, 0.5);
        }
        
        .nav-btn:hover {
            opacity: 1;
            background: rgba(52, 152, 219, 0.1);
        }
        
        /* 响应式设计 */
        @media (max-width: 480px) {
            .chat-app-header {
                height: 60px;
                padding: 10px 15px;
            }
            
            .chat-app-header h1 {
                font-size: 16px;
            }
            
            .chat-app-header h2 {
                font-size: 11px;
            }
            
            .info-banner {
                margin: 65px 10px 8px;
                padding: 10px;
                font-size: 13px;
            }
            
            .info-banner i {
                font-size: 16px;
            }
            
            .back-btn {
                padding: 6px 12px;
                font-size: 13px;
            }
            
            .user-list {
                padding: 10px 8px 70px;
            }
            
            .user-card {
                padding: 12px;
            }
            
            .user-avatar {
                width: 48px;
                height: 48px;
            }
            
            .user-card h3 {
                font-size: 15px;
            }
            
            .user-details {
                grid-template-columns: 1fr;
                gap: 8px;
            }
            
            .detail-item {
                padding: 6px 10px;
            }
            
            .nav-btn {
                padding: 8px 14px;
                font-size: 12px;
            }
            
            .nav-btn i {
                font-size: 20px;
            }
        }
    </style>
</head>
<body>
    <!-- 顶栏 -->
    <header class="chat-app-header">
        <div class="header-left">
            <h1>在线用户</h1>
            <h2>JIILCHAT</h2>
        </div>
    </header>
    
    <!-- 顶部提示信息 -->
    <div class="info-banner">
        <i class="fas fa-info-circle"></i>
        <div class="info-banner-content">
            两分钟无活动自动判定离线
        </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list">
        <?php foreach ($sortedUsers as $username): ?>
            <?php 
            $isOnline = isUserOnline($username, $onlineUsers);
            $lastActive = $onlineUsers[$username]['last_active'] ?? 0;
            $createdAt = getUserRegistrationTime($username);
            $avatarPath = getUserAvatar($username);
            ?>
            
            <div class="user-card <?= $isOnline ? 'online' : '' ?>">
                <div class="user-avatar">
                    <img src="<?= $avatarPath ?>" alt="<?= htmlspecialchars($username) ?>的头像">
                </div>
                
                <div class="user-info">
                    <h3><?= htmlspecialchars($username) ?></h3>
                    
                    <div class="online-indicator">
                        <span class="online-dot <?= $isOnline ? 'online' : 'offline' ?>"></span>
                        <?= $isOnline ? '在线' : '离线' ?>
                    </div>
                    
                    <div class="user-details">
                        <div class="detail-item">
                            <div class="detail-label">注册时间</div>
                            <div class="detail-value time-value">
                                <?= date('Y-m-d H:i', $createdAt) ?>
                            </div>
                        </div>
                        
                        <div class="detail-item">
                            <div class="detail-label">最后活动</div>
                            <div class="detail-value time-value">
                                <?= $lastActive ? date('Y-m-d H:i', $lastActive) : '从未活动' ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
        <?php if (empty($sortedUsers)): ?>
            <div class="user-card">
                <div style="text-align: center; padding: 30px; color: #a0c6ff;">
                    <i class="fas fa-user-slash" style="font-size: 48px; margin-bottom: 15px;"></i>
                    <h3>没有注册用户</h3>
                    <p>当用户注册后，他们将出现在此处</p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- 底部导航 -->
    <footer>
        <button class="nav-btn" onclick="location.href='index.php'">
            <i class="fas fa-home"></i>
            <span>主页</span>
        </button>
        <button class="nav-btn active">
            <i class="fas fa-users"></i>
            <span>用户</span>
        </button>

    </footer>
    
    <script>
        // 每30秒自动刷新页面
        setInterval(() => {
            location.reload();
        }, 30000);
    </script>
</body>
</html>